package RegisteredUserServlet;

import java.io.IOException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entities.Utente;

import sessions.LoginSystemRemote;

public class CreateModifyPageServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		showUser(getUser(request), request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		showUser(getUser(request), request, response);
	}

	private Utente getUser(HttpServletRequest request) {
		Context jndiCtx;
		int id = (Integer) request.getSession().getAttribute("id");
		try {
			jndiCtx = new InitialContext();
			LoginSystemRemote loginSystemRemote = (LoginSystemRemote) jndiCtx
					.lookup("Progetto/LoginSystem/remote");
			return loginSystemRemote.getUserByID(id);
		} catch (Exception e) {
			System.out.println("Errore nel binding remoto");
			return null;
		}
	}

	private void showUser(Utente user, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			if (user != null)
				request.getSession().setAttribute("user", user);
			else
				request.getSession().setAttribute("state", "error");
			response.sendRedirect("/ProgettoWeb/RegisteredUser/ModificaProfilo.jsp");
		} catch (Exception e) {
			System.out.println("Errore nel binding remoto");
		}
	}
}
